var r = require;
r(['/assets/js/require.config.js'], function(config) {
  r.config(config);
  
  r(['refresh']);
  r(['lodash', 'underscore', 'moment'], function(_, __, moment) { window._ = _; window.__ = __; window.moment = moment; })
  
  window.$env = {};
  r(['backbone', 'underscore', 'jquery', 'init'], App);
});


function App(Backbone, _, $) {

  var MenuModel = Backbone.Model.extend({});

  var menuModel = new MenuModel({
    title: 'Clustered Application',
    data: '2019-5-15 15:57'
  });

  var LayoutView = Backbone.View.extend({
    el: '#container',
    template: _.template('<div class="row"><div class="col-md-9" id="main">{{title}}</div><div class="col-md-3"><div id="menu"></div></div></div>'),
    initialize: function() {
      this.$el.addClass('container').html(this.template(this.model.toJSON()));
    },
    clean: function() {
      $('#main').html(this.model.attributes.title);
    },
    render: function() {
      require(['json!./v/config.json', './js/menu'], function(data, menu) {
        menu(data);
      })

      return this;
    }
  })

  var AppRouter = Backbone.Router.extend({
    routes: {
      ":clazz/:type": "loadView",
      "*actions": "defaultRoute"
    },
    initialize: function() {
      this.layout = new LayoutView({ model: menuModel }).render();
    },
    defaultRoute: function(actions) {
      if (this.layout) {
        this.layout.clean();
      }
    },
    loadView: function(clazz, type) {
      //对应的链接为<a href="#/clazz/type">Load clazz/type View</a>
      require(['./v/' + clazz + '/' + type + '/js/app'], function(app) {
        if (_.isFunction(app)) {
          var view = new app({ model: menuModel });
          if (view.render) {
            view.render();
          }
        } else if (_.isObject(app) && _.isFunction(app.render)) {
          app.render({ model: menuModel })
        }
      });
    }
  });

  var app_router = new AppRouter;
  Backbone.history.start();
  window.app_router = app_router;
}